import * as echarts from '../../ec-canvas/echarts';
import router from "../../utils/router";
import store from '../../utils/store'
import {
    getDay
} from '../../utils/date'
import dayjs from "dayjs";
// import utc from 'dayjs/plugin/utc'
// import timezone from 'dayjs/plugin/timezone'
// dayjs.extend(utc)
// dayjs.extend(timezone)
const app = getApp()
const Api = app.Api
Page({
    data: {
        role: '', // 用户权限
        allCars: 0, // 所有车辆
        ec: {
            lazyLoad: true
        },
        totalCount: 0,
        dataSource: [],
        pageNum: 1,
        pageSize: 10,
        page: 1,
        total: 0,
        date: '',
        xAxisArr: [], // x轴的数组
        yAxisArr: [], // y轴的数组
        startTime: '',
        endTime: '',
        noEchartsData: false
    },

    async onLoad() {
        this.echartsRef = this.selectComponent("#mychart")
        console.log(this.echartsRef)
        const startTime = store.getItem('startTime') || getDay(-7)
        const endTime = store.getItem('endTime') || getDay(0)
        this.setData({
            startTime,
            endTime
        })
    },

    async getAllCars() {
        const startTime = '2019-01-01'
        const factoryId = store.getItem("factoryId")
        const res = await app.clientPost(`${app.ClientApi.getAllCarList}/page-num/1/page-size/10/factoryId/${factoryId}`, {
            startTime: startTime + " 00:00:00",
            endTime: dayjs().format('YYYY-MM-DD') + " 23:59:59"
        })
        this.setData({
            allCars: res.total
        })
    },
    async getOrderList() {
        const factoryId = store.getItem("factoryId")
        const res = await app.clientPost(`${app.ClientApi.getTodayCarNum}/page-num/${this.data.pageNum}/page-size/${this.data.pageSize}/factoryId/${factoryId}`, {
            startTime: store.getItem('startTime'),
            endTime: store.getItem('endTime'),
            status: '6'
        })
        const dataSource = res.list.slice(0, 3)
        this.setData({
            dataSource
        })
    },
    transFormList(list) {
        const titleList = list.map((item) => {
            return {
                id: item.taskId,
                title: item.taskId
            }
        })
        const nameList = list.map(item => item.name)
        const carList = list.map(item => item.licenseNo)
        const startTimeList = list.map(item => item.startTime)
        const startLoadingTimeList = list.map(item => {
            return dayjs(item.startLoadingTime)
            .format('YYYY-MM-DD HH:mm:ss')
        })
        const endTimeList = list.map(item => item.endTime)
        const itemList = [{
                name: "车道",
                list: nameList
            },
            {
                name: "车牌",
                list: carList
            },
            {
                name: "开始时间",
                list: startTimeList
            },
            {
                name: "结束时间",
                list: endTimeList
            },
            {
                name: "开始装车时间",
                list: startLoadingTimeList
            },
        ]
        this.setData({
            itemList,
            orderTitleList: titleList
        })
    },

    async getLoadingData() {
        const startTime = '2019-01-01'
        const endTime = dayjs().format('YYYY-MM-DD')
        const factoryId = store.getItem("factoryId")
        try {
            const res = await app.clientGet(`${app.ClientApi.getLoadingData}/${startTime}/${endTime}/factoryId/${factoryId}`, {}, {
                loading: false
            })
            const sums = res.map(item => {
                if (item.supplementNumber === undefined) {
                    item.supplementNumber = 0
                }
                return item.coordinateId + item.supplementNumber
            })
            const totalCount = sums.reduce((total, item) => {
                return total + item
            }) / 20
            this.setData({
                totalCount: totalCount
            })
        } catch (e) {
            this.setData({
                totalCount: '暂无数据'
            })
        }
    },

    // 查询图表数据
    async handleSearch() {
        const factoryId = store.getItem("factoryId")
        const start = store.getItem("startTime") || getDay(-7)
        const end = store.getItem("endTime") || getDay(0)
        try {
            const res = await app.clientGet(`${app.ClientApi.getLoadingData}/${start}/${end}/factoryId/${factoryId}`)
            const xAxisArr = res.map(item => item.createdAt.slice(5))
            const yAxisArr = res.map(item => {
                if (item.supplementNumber === undefined) {
                    item.supplementNumber = 0
                }
                return item.coordinateId + item.supplementNumber
            })
            this.setData({
                noEchartsData: false,
                xAxisArr,
                yAxisArr
            })
            this.initCharts()
        } catch (e) {
            this.setData({
                noEchartsData: true,
                xAxisArr: [],
                yAxisArr: []
            })
            console.log('e', e)
        }
    },

    // 初始化图表方法
    initCharts() {
        this.echartsRef.init((canvas, width, height) => {
            const Chart = echarts.init(canvas, null, {
                width: width,
                height: height,
            });
            Chart.clear()
            Chart.setOption(this.getOption())
            return Chart
        })
    },

    getOption() {
        let option = {
            title: {
                text: '',
            },
            grid: {
                left: '15%',
                bottom: '10%',
                top: "15%",
                right: "40"
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: this.data.xAxisArr,
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                type: 'line',
                smooth: true,
                color: '#0065ff',
                data: this.data.yAxisArr,
                label: {
                    show: true,
                    position: 'top',
                    color: 'red'
                }
            }]
        };
        return option
    },

    // 点击累计车辆跳转事件
    toCarList() {
        if (this.data.role === '1') {
            router.push('carlist')
        } else {
            return
        }
    },
    // 点击累计装水泥跳转事件
    toOrderAll() {
        if (this.data.role === '1') {
            router.push('order-all')
        } else {
            return
        }
    },
    // 点击全部订单按钮
    handleRouter() {
        if (this.data.role === '1') {
            router.push('order-all')
        } else {
            return
        }
    },

    // 获取用户权限
    async getUserInfo(phoneNumber) {
        const res = await app.get(`${Api.getUserInfo}?phoneNumber=${phoneNumber}`)
        const role = res[0].jurisdiction
        this.setData({
            role
        })
    },

    async onShow() {
        this.setData({
            xAxisArr: [],
            yAxisArr: []
        })
        const startTime = store.getItem('startTime') || getDay(-7)
        const endTime = store.getItem('endTime') || getDay(0)
        const phoneNumber = store.getItem('phoneNumber')
        this.setData({
            startTime,
            endTime
        })
        await this.getAllCars()
        await this.getOrderList()
        await this.getLoadingData()
        await this.handleSearch()
        await this.getUserInfo(phoneNumber)
    },

    onDisplay() {
        router.push('select-date')
    },

    onUnload() {
        this.setData({
            noEchartsData: false,
        })
    }

});